﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MediaAutomatorLib.ExternalPrograms
{
    public class UTorrentProgram
    {
        private readonly String _hostname;
        private readonly int _port;
        private readonly String _username;
        private readonly String _password;

        private String _token;

        private CookieAwareWebClient _webClient;

        private static readonly Regex TOKEN_REGEX = new Regex(".*<div id='token' style='display:none;'>(.*)</div>.*");

        public UTorrentProgram(String hostname, int port, String username, String password)
        {
            _hostname = hostname;
            _port = port;
            _username = username;
            _password = password;

            _webClient = new CookieAwareWebClient {Credentials = new NetworkCredential(_username, _password)};
        }

        private String GetToken()
        {
            try
            {
                Console.WriteLine("Geting token...");

                Stream stream = _webClient.OpenRead(
                    string.Format("http://{0}:{1}/gui/token.html", _hostname, _port));
                TextReader reader = new StreamReader(stream);
                String request = reader.ReadToEnd();
                Match match = TOKEN_REGEX.Match(request);
                string token = match.Groups[1].Value;
                Console.WriteLine("Token: " + token);
                return token;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return null;
        } 

        public void RemoveTorrent(string torrentHash)
        {
            if (String.IsNullOrEmpty(_token))
                _token = GetToken();

            try
            {
                Console.WriteLine("Geting token...");                
                string url = string.Format("http://{0}:{1}/gui/?token={2}&action=remove&hash={3}", _hostname,
                                           _port, _token, torrentHash);
                Console.WriteLine("URL: " + url);
                Stream stream = _webClient.OpenRead(url);
                //&list=1&cid=1312519173&getmsg=1&t=1352126033270
                TextReader reader = new StreamReader(stream);
                String request = reader.ReadToEnd();
                Console.WriteLine(request);
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private class CookieAwareWebClient : WebClient
        {
            public CookieAwareWebClient()
                : this(new CookieContainer())
            { }
            public CookieAwareWebClient(CookieContainer c)
            {
                this.CookieContainer = c;
            }
            public CookieContainer CookieContainer { get; set; }

            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);
                if (request is HttpWebRequest)
                {
                    (request as HttpWebRequest).CookieContainer = this.CookieContainer;
                }
                return request;
            }
        }
    }
}
